<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: UserWechatsController.php
// +----------------------------------------------------------------------
// | Author: gxs
// +----------------------------------------------------------------------
// | Description: 用户微信相关
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019/1/5 Author: gxs Modification: 创建
// +----------------------------------------------------------------------

namespace App\Http\Controllers\Frontend\V10\Users;

use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\V10\Users\UserWechatsRequest;
use App\Models\User as UserModel;
use App\Models\User;
use App\Models\UserGlobal;
use App\Models\UserLoginLog;
use App\Models\UserWechat as UserWechatModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserWechatsController extends Controller
{
    /**
     * UserWechatsController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth:api')->except([
            'store',
            'show',
            'update',
        ]);
        $this->middleware('empty_string');
    }

    /**
     * 微信登录 && 验证是否绑定
     *
     * @param UserWechatsRequest $request
     * @return mixed
     */
    public function store(UserWechatsRequest $request)
    {
        $params = $this->extractInputFromRules($request,$request->rules());
        $openid = $params['openid'];

        $bind_status = UserWechatModel::BIND_STATUS_ONE;
        $token = '';
        $model = UserWechatModel::where('openid', $openid)->first();
        if (empty($model)) {
            $model = UserWechatModel::create($params);
            Log::debug('user_wechat_store', ['params'=>$params]);
        } else {
            if (!empty($model['uid'])) {
                $bind_status = UserWechatModel::BIND_STATUS_TWO;
                $user_model = User::find($model['uid']);
                $token = auth('api')->login($user_model);
                UserModel::updateTokenRecord($user_model,$token);
                UserLoginLog::createLog($user_model, UserLoginLog::TYPE_WECHAT); //登录log
                UserGlobal::jpushDataUpdate($user_model, $request); //极光相关更新
                Log::debug('user_wechat_token', ['uid' => $model['uid'],'token'=>$token]);
            } else {
                $bind_status = UserWechatModel::BIND_STATUS_ONE;
            }
        }

        $result = [
            'id' => $model['id'],
            'bind_status' => $bind_status,
            'token' => $token,
        ];
        return respond($result);
    }

    /**
     * 手机号是否已存在
     *
     * @param UserWechatsRequest $request
     * @param $id
     * @return mixed
     */
    public function show(UserWechatsRequest $request, $id)
    {
        $params = $this->extractInputFromRules($request,$request->rules());
        $phone_num = $params['phone_num'];
        $user_model = UserModel::where('phone_num', $phone_num)->first();
        if (!empty($user_model)) {
            //检测这个用户是否已绑定
            $user_wechat_model = UserWechatModel::where('uid', $user_model['id'])->first();
            if (!empty($user_wechat_model))
                return failed('该用户已绑定其他微信!');
        }
        if (empty($user_model))
            $exists_status = UserModel::MOBILE_EXISTS_TWO;
        else
            $exists_status = UserModel::MOBILE_EXISTS_ONE;
        $result = [
            'id' => $id,
            'exists_status' => $exists_status,
        ];
        return respond($result);
    }

    /**
     * 账户&微信绑定操作
     *
     * @param UserWechatsRequest $request
     * @param $id
     * @return mixed
     */
    public function update(UserWechatsRequest $request, $id)
    {
        $wechat_model = UserWechatModel::find($id);
        if (empty($wechat_model))
            return failed('微信记录不存在!');
        if (!empty($wechat_model['uid']))
            return failed('该用户已绑定其他微信!');
        $method = $request->method();
        if ('PUT' === $method) {
            //无账号注册绑定
            $params = $this->extractInputFromRules($request,$request->rules());
            $verify = verifyPhoneCode($params['phone_num'],$params['code']);
            if (!$verify)
                return failed('验证码错误');
            //注册用户 && 创建用户全局状态
            $token = '';
            $user_model = '';
            DB::transaction(function () use ($params, $wechat_model, &$token, &$user_model) {
                $user_model = UserModel::createUser($params);
                $token = auth('api')->login($user_model);
                //绑定
                $wechat_model->uid = $user_model['id'];
                $wechat_model->save();
            });
        } else {
            //PATCH 已有账号直接绑定
            $params = $request->only(['phone_num', 'password']);
            $token = auth('api')->attempt($params);
            if (!$token)
                return failed('手机号或密码错误');
            $user_model = auth('api')->user();
            //绑定
            $wechat_model->uid = auth('api')->id();
            $wechat_model->save();
        }
        UserModel::updateTokenRecord($user_model,$token); //更新用户token
        UserLoginLog::createLog($user_model, UserLoginLog::TYPE_WECHAT); //登录log
        UserGlobal::jpushDataUpdate($user_model, $request); //极光相关更新
        Log::debug('user_wechat_token', ['uid' => $wechat_model['uid'],'token'=>$token]);
        return respond([
            'user'=>UserModel::getCurrentUserDetailByApp($user_model),
            'token'=>$token,
        ]);
    }
}